package com.myself.community.controller;

import com.myself.community.entity.*;
import com.myself.community.event.EventProducer;
import com.myself.community.service.CommentService;
import com.myself.community.service.DiscussPostService;
import com.myself.community.service.LikeService;
import com.myself.community.service.UserService;
import com.myself.community.utils.Code;
import com.myself.community.utils.CommunityUtil;
import com.myself.community.utils.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Controller
@RequestMapping("/discuss")
public class DiscussPostController{

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private UserService userService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private EventProducer eventProducer;

    /**
     * 处理新增帖子请求
     * @param title  题目
     * @param content 内容
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public String addDiscussPost(String title, String content) {
        //获取当前用户数据
        User user = hostHolder.getUser();
        if (user == null) {
            //未登录
            return CommunityUtil.getJSONString(403, "你还没有登录哦!");
        }
        //封装帖子对象
        DiscussPost post = new DiscussPost();
        post.setUserId(user.getId());
        post.setTitle(title);
        post.setContent(content);
        post.setCreateTime(new Date());
        //存入数据库
        discussPostService.addDiscussPost(post);

        //触发发帖事件
        Event event = new Event()
                .setTopic(Code.TOPIC_PUBLISH)
                .setUserId(user.getId())
                .setEntityType(Code.ENTITY_TYPE_POST)
                .setEntityId(post.getId());
        eventProducer.sendEvent(event);

        // 报错的情况,将来统一处理.
        return CommunityUtil.getJSONString(Code.OK, "发布成功!");
    }

    /**
     * 帖子详情请求：内容，评论回复
     * @param discussPostId
     * @param model
     * @param page
     * @return
     */
    @GetMapping("/detail/{discussPostId}")
    public String getDiscussPost(@PathVariable("discussPostId") int discussPostId, Model model, Page page) {
        // 查询出帖子
        DiscussPost post = discussPostService.findDiscussPostById(discussPostId);
        //将数据给到模板
        model.addAttribute("post", post);

        // 查询出帖子的作者
        User user = userService.findUserById(post.getUserId());
        model.addAttribute("user", user);

        //帖子赞的数量
        long likeCount = likeService.findEntityLikeCount(Code.ENTITY_TYPE_POST, discussPostId);
        model.addAttribute("likeCount", likeCount);
        // 当前用户对这个帖子点赞状态
        int likeStatus = hostHolder.getUser() == null ? 0 :
                likeService.findEntityLikeStatus(hostHolder.getUser().getId(), Code.ENTITY_TYPE_POST, discussPostId);
        model.addAttribute("likeStatus", likeStatus);

        // 评论分页信息
        page.setLimit(5);
        page.setPath("/discuss/detail/" + discussPostId);
        page.setRows(post.getCommentCount());//这个帖子下的评论总数

        // 评论: 给帖子的评论
        // 回复: 给评论的评论
        // 评论列表:给帖子的评论
        List<Comment> commentList = commentService.findCommentsByEntity(
                Code.ENTITY_TYPE_POST, post.getId(), page.getOffset(), page.getLimit());
        // 评论VO列表
        List<Map<String, Object>> commentVoList = new ArrayList<>();
        if (commentList != null) {
            //将给帖子的评论存入一个map中
            for (Comment comment : commentList) {
                // 评论VO
                Map<String, Object> commentVo = new HashMap<>();
                // 评论内容
                commentVo.put("comment", comment);
                // 评论帖子作者信息
                commentVo.put("user", userService.findUserById(comment.getUserId()));

                // 点赞数量
                likeCount = likeService.findEntityLikeCount(Code.ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("likeCount", likeCount);
                // 点赞状态
                likeStatus = hostHolder.getUser() == null ? 0 :
                        likeService.findEntityLikeStatus(hostHolder.getUser().getId(), Code.ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("likeStatus", likeStatus);

                // 回复列表：给评论的评论
                List<Comment> replyList = commentService.findCommentsByEntity(
                        Code.ENTITY_TYPE_COMMENT, comment.getId(), 0, Integer.MAX_VALUE);
                // 回复VO列表
                List<Map<String, Object>> replyVoList = new ArrayList<>();
                if (replyList != null) {
                    for (Comment reply : replyList) {
                        Map<String, Object> replyVo = new HashMap<>();
                        // 回复的内容
                        replyVo.put("reply", reply);
                        // 回复评论的作者信息
                        replyVo.put("user", userService.findUserById(reply.getUserId()));
                        // 回复目标用户信息
                        User target = reply.getTargetId() == 0 ? null : userService.findUserById(reply.getTargetId());
                        replyVo.put("target", target);

                        // 点赞数量
                        likeCount = likeService.findEntityLikeCount(Code.ENTITY_TYPE_COMMENT, reply.getId());
                        replyVo.put("likeCount", likeCount);
                        // 点赞状态
                        likeStatus = hostHolder.getUser() == null ? 0 :
                                likeService.findEntityLikeStatus(hostHolder.getUser().getId(), Code.ENTITY_TYPE_COMMENT, reply.getId());
                        replyVo.put("likeStatus", likeStatus);

                        replyVoList.add(replyVo);
                    }
                }
                commentVo.put("replys", replyVoList);

                // 回复数量
                int replyCount = commentService.findCommentCount(Code.ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("replyCount", replyCount);

                commentVoList.add(commentVo);
            }
        }

        model.addAttribute("comments", commentVoList);

        return "/site/discuss-detail";
    }

}
